/*
 * @(#)JSonResult.java $version 2010. 8. 11
 *
 * Copyright 2007-2010 NHN Corp. All rights Reserved. 
 * NHN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package com.nhncorp.usf.core.result.direct;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.StringTokenizer;

import javax.servlet.http.HttpServletResponse;

import org.codehaus.jackson.map.ObjectMapper;

import com.nhncorp.lucy.common.util.DataMap;
import com.nhncorp.lucy.web.helper.ServletHelper;
import com.nhncorp.usf.core.config.runtime.ResultPageInfo;
import com.nhncorp.usf.core.config.runtime.ResultPageInfos;
import com.nhncorp.usf.core.util.StringUtil;

/**
 * {@link ResultPageInfos}의 Path 에 정의된 내용을 내보내는 {@link Result}.
 * 
 * @author Web Platform Development Team
 */
@SuppressWarnings("serial")
public class JSonResult extends AbstractDirectResult {

    /**
     * 전달된 {@link DataMap} 정보를 {@link JSONObject} 로 변환하여 결과 페이지로 내보냄.
     * 
     * @param resultPage
     *            the page information
     * @param dataMap
     *            the usf result data
     * @throws Exception
     *             the Exception
     */
    public void execute(ResultPageInfo resultPage, Map<String, Object> dataMap)
            throws Exception {
        Properties properties = resultPage.getProperties();
        String srcData = properties.getProperty("src");

        if (StringUtil.isEmpty(srcData)) {
            throw new Exception("src property is not correct");
        }

        HttpServletResponse response = ServletHelper.getResponse();
        response.setContentType("text/html; charset=" + getPageEncoding());

        StringTokenizer token = new StringTokenizer(srcData, ",");
        Map<String, Object> map = new HashMap<String, Object>();
        ObjectMapper om = new ObjectMapper();

        while (token.hasMoreTokens()) {
            String jsonObjKey = token.nextToken();
            map.put(jsonObjKey, dataMap.get(jsonObjKey));
        }

        if (map.size() == 0) {
            throw new Exception("src property is not correct");
        }

        if (map.size() == 1) {
            Object value = map.get(srcData);

            if (value == null) {
                throw new Exception("src property is not correct");
            }

            response.getWriter().write(om.writeValueAsString(value));
        } else {
            response.getWriter().write(om.writeValueAsString(map));
        }
    }
}
